package com.example.layoutmanagerdemo.detach;

import androidx.core.view.ViewCompat;

import static com.example.layoutmanagerdemo.detach.RecyclerView.POST_UPDATES_ON_ANIMATION;

class RecyclerViewDataObserver extends AdapterDataObserver {
    private RecyclerView recyclerView;

    RecyclerViewDataObserver(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    @Override
    public void onChanged() {
        recyclerView.assertNotInLayoutOrScroll(null);
        recyclerView.mState.mStructureChanged = true;

        recyclerView.processDataSetCompletelyChanged(true);
        if (!recyclerView.mAdapterHelper.hasPendingUpdates()) {
            recyclerView.requestLayout();
        }
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
        recyclerView.assertNotInLayoutOrScroll(null);
        if (recyclerView.mAdapterHelper.onItemRangeChanged(positionStart, itemCount, payload)) {
            triggerUpdateProcessor();
        }
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        recyclerView.assertNotInLayoutOrScroll(null);
        if (recyclerView.mAdapterHelper.onItemRangeInserted(positionStart, itemCount)) {
            triggerUpdateProcessor();
        }
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        recyclerView.assertNotInLayoutOrScroll(null);
        if (recyclerView.mAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) {
            triggerUpdateProcessor();
        }
    }

    @Override
    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
        recyclerView.assertNotInLayoutOrScroll(null);
        if (recyclerView.mAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) {
            triggerUpdateProcessor();
        }
    }

    void triggerUpdateProcessor() {
        if (POST_UPDATES_ON_ANIMATION && recyclerView.mHasFixedSize && recyclerView.mIsAttached) {
            ViewCompat.postOnAnimation(recyclerView, recyclerView.mUpdateChildViewsRunnable);
        } else {
            recyclerView.mAdapterUpdateDuringMeasure = true;
            recyclerView.requestLayout();
        }
    }
}